/**
 * DeepSeek专项测试服务 - 特定的连通性和功能测试
 */
import { message } from 'antd';
import modelDiscoveryService from './model-discovery.service';

interface DeepSeekTestConfig {
  baseUrl: string;
  apiKey: string;
  modelName?: string;
}

interface DeepSeekTestResult {
  success: boolean;
  connectivity: boolean;
  modelDiscovery: boolean;
  chatCompletion: boolean;
  streaming: boolean;
  errors: string[];
  models: string[];
  responseTime: number;
  details: Record<string, any>;
}

class DeepSeekTesterService {
  private readonly DEFAULT_BASE_URL = 'https://api.deepseek.com';
  private readonly DEFAULT_MODEL = 'deepseek-chat';
  
  /**
   * 运行完整的DeepSeek测试套件
   */
  async runFullTest(config: DeepSeekTestConfig): Promise<DeepSeekTestResult> {
    const startTime = Date.now();
    const result: DeepSeekTestResult = {
      success: false,
      connectivity: false,
      modelDiscovery: false,
      chatCompletion: false,
      streaming: false,
      errors: [],
      models: [],
      responseTime: 0,
      details: {}
    };
    
    try {
      // 1. 连通性测试
      console.log('开始DeepSeek连通性测试...');
      result.connectivity = await this.testConnectivity(config);
      if (!result.connectivity) {
        result.errors.push('连通性测试失败');
      }
      
      // 2. 模型发现测试
      console.log('开始DeepSeek模型发现测试...');
      const discoveryResult = await this.testModelDiscovery(config);
      result.modelDiscovery = discoveryResult.success;
      result.models = discoveryResult.models;
      if (!result.modelDiscovery) {
        result.errors.push('模型发现失败');
      }
      
      // 3. 聊天补全测试
      console.log('开始DeepSeek聊天补全测试...');
      const chatResult = await this.testChatCompletion(config);
      result.chatCompletion = chatResult.success;
      result.details.chatResponse = chatResult.response;
      if (!result.chatCompletion) {
        result.errors.push('聊天补全测试失败: ' + chatResult.error);
      }
      
      // 4. 流式输出测试
      console.log('开始DeepSeek流式输出测试...');
      const streamResult = await this.testStreaming(config);
      result.streaming = streamResult.success;
      result.details.streamChunks = streamResult.chunks;
      if (!result.streaming) {
        result.errors.push('流式输出测试失败: ' + streamResult.error);
      }
      
      // 计算总体成功率
      const successCount = [
        result.connectivity,
        result.modelDiscovery,
        result.chatCompletion,
        result.streaming
      ].filter(Boolean).length;
      
      result.success = successCount >= 3; // 至少3项成功
      result.responseTime = Date.now() - startTime;
      
      console.log('DeepSeek测试完成:', result);
      
    } catch (error) {
      result.errors.push(`测试异常: ${error instanceof Error ? error.message : String(error)}`);
      result.responseTime = Date.now() - startTime;
    }
    
    return result;
  }
  
  /**
   * 测试基础连通性
   */
  private async testConnectivity(config: DeepSeekTestConfig): Promise<boolean> {
    try {
      const response = await fetch(`${config.baseUrl}/models`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        signal: AbortSignal.timeout(10000)
      });
      
      return response.status === 200 || response.status === 401; // 401也说明能连通
    } catch (error) {
      console.error('DeepSeek连通性测试失败:', error);
      return false;
    }
  }
  
  /**
   * 测试模型发现
   */
  private async testModelDiscovery(config: DeepSeekTestConfig): Promise<{
    success: boolean;
    models: string[];
    error?: string;
  }> {
    try {
      const discovery = await modelDiscoveryService.discoverModels(
        'deepseek',
        config.baseUrl,
        config.apiKey
      );
      
      if (discovery.success && discovery.models.length > 0) {
        return {
          success: true,
          models: discovery.models.map((m: any) => m.id || m.name)
        };
      } else {
        return {
          success: false,
          models: [],
          error: discovery.error || '未发现可用模型'
        };
      }
    } catch (error) {
      return {
        success: false,
        models: [],
        error: error instanceof Error ? error.message : '模型发现异常'
      };
    }
  }
  
  /**
   * 测试聊天补全
   */
  private async testChatCompletion(config: DeepSeekTestConfig): Promise<{
    success: boolean;
    response?: string;
    error?: string;
  }> {
    try {
      const response = await fetch(`${config.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: config.modelName || this.DEFAULT_MODEL,
          messages: [
            {
              role: 'user',
              content: '你好，请简单介绍一下你自己。'
            }
          ],
          max_tokens: 100,
          temperature: 0.1
        }),
        signal: AbortSignal.timeout(30000)
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const data = await response.json();
      
      if (data.choices && data.choices[0] && data.choices[0].message) {
        return {
          success: true,
          response: data.choices[0].message.content
        };
      } else {
        return {
          success: false,
          error: '响应格式异常'
        };
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '聊天补全测试异常'
      };
    }
  }
  
  /**
   * 测试流式输出
   */
  private async testStreaming(config: DeepSeekTestConfig): Promise<{
    success: boolean;
    chunks: number;
    error?: string;
  }> {
    try {
      const response = await fetch(`${config.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: config.modelName || this.DEFAULT_MODEL,
          messages: [
            {
              role: 'user',
              content: '请数数字1到5。'
            }
          ],
          max_tokens: 50,
          temperature: 0.1,
          stream: true
        }),
        signal: AbortSignal.timeout(30000)
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      if (!response.body) {
        throw new Error('响应体为空');
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let chunks = 0;
      
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n').filter(line => line.trim());
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              if (data === '[DONE]') continue;
              
              try {
                const parsed = JSON.parse(data);
                if (parsed.choices && parsed.choices[0]) {
                  chunks++;
                }
              } catch (e) {
                // 忽略解析错误
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
      
      return {
        success: chunks > 0,
        chunks
      };
    } catch (error) {
      return {
        success: false,
        chunks: 0,
        error: error instanceof Error ? error.message : '流式输出测试异常'
      };
    }
  }
  
  /**
   * 获取DeepSeek特定的错误码说明
   */
  getErrorCodeExplanation(statusCode: number): string {
    const explanations: Record<number, string> = {
      400: '请求参数错误，请检查模型名称和参数格式',
      401: 'API密钥无效或未提供，请检查密钥是否正确',
      403: '访问被拒绝，可能是密钥权限不足或账户状态异常',
      404: '模型不存在，请检查模型名称是否正确',
      429: '请求频率过高，请稍后重试或升级账户套餐',
      500: 'DeepSeek服务内部错误，请稍后重试',
      503: 'DeepSeek服务暂时不可用，请稍后重试'
    };
    
    return explanations[statusCode] || `未知错误代码: ${statusCode}`;
  }
  
  /**
   * 生成DeepSeek使用建议
   */
  generateUsageRecommendations(testResult: DeepSeekTestResult): string[] {
    const recommendations: string[] = [];
    
    if (!testResult.connectivity) {
      recommendations.push('检查网络连接和API基础URL设置');
      recommendations.push('确认防火墙未阻止访问api.deepseek.com');
    }
    
    if (!testResult.modelDiscovery) {
      recommendations.push('验证API密钥是否正确且有效');
      recommendations.push('检查账户状态和权限设置');
    }
    
    if (!testResult.chatCompletion) {
      recommendations.push('尝试使用不同的模型名称（如deepseek-chat, deepseek-coder）');
      recommendations.push('减少max_tokens值或调整其他参数');
    }
    
    if (!testResult.streaming) {
      recommendations.push('确认网络支持流式传输');
      recommendations.push('检查防火墙或代理设置');
    }
    
    if (testResult.responseTime > 5000) {
      recommendations.push('网络延迟较高，考虑使用国内镜像或代理');
    }
    
    if (testResult.success) {
      recommendations.push('✅ DeepSeek配置测试通过，可以正常使用');
      recommendations.push('💡 建议定期检查模型状态以确保稳定性');
    }
    
    return recommendations;
  }
  
  /**
   * 快速测试DeepSeek配置
   */
  async quickTest(baseUrl: string, apiKey: string): Promise<{
    success: boolean;
    message: string;
    details?: any;
  }> {
    try {
      const result = await this.testConnectivity({ baseUrl, apiKey });
      
      if (result) {
        return {
          success: true,
          message: 'DeepSeek连接测试成功',
          details: { responseTime: Date.now() }
        };
      } else {
        return {
          success: false,
          message: 'DeepSeek连接测试失败，请检查URL和密钥'
        };
      }
    } catch (error) {
      return {
        success: false,
        message: `测试异常: ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }
}

export default new DeepSeekTesterService();